import React, { useState, useEffect, useRef } from 'react';
import styles from './style.less';
import { Table, Space, Row, Col, Button, Switch, message } from 'antd';
import Query from '@/components/Global/Query/index';
import Footer from '@/components/Global/Footer';
import { ColumnsType } from 'antd/es/table';
import { PlanColumn, PlanList, PlanParams } from './data';
import { changeStatus, delPlan, getPlatForms, getPlatStatus, getTable, planExport } from './service';
import { history } from 'umi';
// import moment from 'moment';
import ModalComp from '@/components/Global/Modal/index';

let queryList = [];

export default function PlanTable(props: any) {
  console.log(props, '计划props');

  const [tableData, setTableData] = useState([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const btnRef = useRef<any>(null!);
  const [total, setTotal] = useState(0);
  const [modalFlag, setModalFlag] = useState(false);
  const [type, setType] = useState('');
  const [delText, setDelText] = useState('');
  const [delTitle, setDelTitle] = useState('');
  const [endText, setEndText] = useState('');
  const [endTitle, setEndTitle] = useState('');
  const [record, setRecord] = useState<PlanList>({});
  const [platForms, setPlatForms] = useState<any>([]);
  const [platStatus, setPlatStatus] = useState<any>([]);

  console.log(btnRef)
  // const form = btnRef.current.getForm();

  const params = {
    planName: '',
    planStatus: [],
    platformAccount: '',
    platformChannel: '',
    startDate: '2021-07-19',
    endDate: '2021-07-19',
    page: page,
    rows: pageSize,
  };

  let columns: ColumnsType<PlanColumn> = [
    {
      title: '计划名称',
      dataIndex: 'planName',
      key: 'planName',
      // className: `${styles.content} ${styles.plan}`,
      className: styles.content,
      width: 210,
      ellipsis: true
      // align: 'center'
      // onCell(record, rowIndex) {
      //   console.log(record, rowIndex)
      //   return {
      //       className: styles[`.....`],
      //   };
      // }
    },
    {
      title: '计划状态',
      dataIndex: 'dataStatus',
      key: 'dataStatus',
      // align: 'center',
      className: styles.content,
      width: 150,
      render: (text: string, record: any) => (
        <span>{text === '1' ? '未推广' : text === '2' ? '已推广' : text === '3' ? '推广失败' : text === '4' ? '绑定账号待推广' : '-'}</span>
      )
    },
    {
      title: '推广平台',
      dataIndex: 'platformChannel',
      key: 'platformChannel',
      // align: 'center',
      className: styles.content,
      width: 200,
      render: (text: string, record: any) => (
        <span>{text === '1' ? '360' : text === '2' ? '百度' : text === '3' ? '搜狗' : '-'}</span>
      )
    },
    {
      title: '推广账号',
      dataIndex: 'platformAccount',
      key: 'platformAccount',
      // align: 'center'
      className: styles.content,
      width: 300,
    },
    {
      title: '平台状态',
      dataIndex: 'planStatus',
      key: 'planStatus',
      // align: 'center'
      className: styles.content,
      width: 150,
    },
    {
      title: '启用/暂停',
      dataIndex: 'pause',
      key: 'pause',
      // align: 'center'
      className: styles.content,
      width: 150,
      render(text: string, record: any) {
        // console.log(text, row, index);
        return text ? (
          <>
            <Switch defaultChecked={text === '2'} onChange={(checked: boolean) => { onChange(checked, record) }} />
            <label>{text === '1' ? '启用' : '停用'}</label>
          </>
        ) : (
          <div>-</div>
        );
      },
    },
    {
      title: '业务类型',
      dataIndex: 'business',
      key: 'business',
      // align: 'center'
      className: styles.content,
      width: 100,
    },
    {
      title: '关联楼盘',
      dataIndex: 'houses',
      key: 'houses',
      // align: 'center'
      className: styles.content,
      width: 300,
    },
    {
      title: '总预算（元/天）',
      dataIndex: 'budget',
      key: 'budget',
      sorter: (a, b) => a.budget - b.budget,
      // align: 'center'
      className: styles.content,
      width: 150,
    },
    {
      title: '投放区域',
      dataIndex: 'area',
      key: 'area',
      // align: 'center'
      className: styles.content,
      width: 150,
    },
    {
      title: '投放时段',
      dataIndex: 'area',
      key: 'area',
      // align: 'center'
      className: styles.content,
      width: 150,
    },
    {
      title: '展示次数',
      dataIndex: 'showCount',
      key: 'showCount',
      sorter: (a, b) => a.showCount - b.showCount,
      // align: 'center'
      className: styles.content,
      width: 150,
    },
    {
      title: '点击次数',
      dataIndex: 'clickCount',
      key: 'clickCount',
      sorter: (a, b) => a.clickCount - b.clickCount,
      // align: 'center'
      className: styles.content,
      width: 150,
    },
    {
      title: '点击率',
      dataIndex: 'clickNate',
      key: 'clickNate',
      sorter: (a, b) => a.clickNate - b.clickNate,
      // align: 'center'
      className: styles.content,
      width: 150,
    },
    {
      title: '操作',
      key: 'operation',
      // align: 'center',
      className: `${styles.content} ${styles.action}`,
      width: 130,
      fixed: 'right',
      render: (text: string, record: any) => (
        // text:string, record:object
        <Space size="middle">
          <a onClick={() => { updateClick(record) }}>编辑</a>
          <a onClick={() => { modalClick(record, 'del') }}>删除</a>
        </Space>
      ),
    }
  ];

  // 判断是否从账号管理进入
  if (props.loginFlag === true) {
    columns = columns.filter(item => item.title !== '推广平台');
    queryList = [
      {
        name: 'planName',
        label: '计划名称',
        type: 'input',
        linkAge: false,
        tips: '请输入计划名称',
        colNum: 5
      },
      {
        name: 'planStatus',
        label: '计划状态',
        type: 'select',
        tips: '请选择计划状态',
        mode: 'multiple',
        children: platStatus,
        linkAge: false,
        colNum: 5
      },
      {
        name: 'time',
        label: '统计时间',
        type: 'date',
        tips: '请选择计划状态',
        colNum: 8,
        dateTips: '请选择',
        selDefaultValue: '0',
        linkAge: false,
        dateChildren: [
          {
            value: '0',
            label: '昨日',
          },
          {
            value: '1',
            label: '最近7天',
          },
          {
            value: '2',
            label: '最近30天',
          },
          {
            value: '3',
            label: '最近90天',
          }
        ]
      }
    ];
  } else {
    queryList = [
      {
        name: 'planName',
        label: '计划名称',
        type: 'input',
        linkAge: false,
        tips: '请输入计划名称',
        colNum: 4
      },
      {
        name: 'platformChannel',
        label: '推广平台',
        type: 'select',
        tips: '请选择推广平台',
        colNum: 4,
        linkAge: true,
        children: platForms
      },
      {
        name: 'planStatus',
        label: '计划状态',
        type: 'select',
        tips: '请选择计划状态',
        mode: 'multiple',
        colNum: 4,
        linkAge: false,
        children: platStatus
      },
      {
        name: 'time',
        label: '统计时间',
        type: 'date',
        colNum: 7,
        tips: '请选择计划状态',
        dateTips: '请选择',
        selDefaultValue: '0',
        linkAge: false,
        dateChildren: [
          {
            value: '0',
            label: '昨日',
          },
          {
            value: '1',
            label: '最近7天',
          },
          {
            value: '2',
            label: '最近30天',
          },
          {
            value: '3',
            label: '最近90天',
          }
        ]
      }
    ];
  };

  // 获取第三方平台
  const getPlatOptions = () => {
    getPlatForms({}).then(res => {
      console.log(res, '第三方平台结果');
      const newOptions = res && res.map((item: any) => ({ key: item.platformType, label: item.platformName, value: item.platformType }));
      setPlatForms(newOptions);
    });
  }

  const selectProp = (value: string) => {
    console.log(value)
    const newValue = Number(value);
    getPlanStatusOptions(newValue, 1);
  }

  // 获取第三方状态
  const getPlanStatusOptions = (platType: number, pageType: number) => {
    const params = {
      promoteType: pageType,
      platformType: platType
    }
    getPlatStatus(params).then(res => {
      console.log(res, '第三方状态结果');
      const newOptions = res.map((item: any) => ({ key: item.statusCode, label: item.statusValue, value: item.statusCode }));
      setPlatStatus(newOptions);
    })
  }

  // 获取表格数据
  const getTableData = (params: PlanParams) => {
    getTable(params).then((res) => {
      console.log(res, '请求结果');
      if (res) {
        setTableData(res.list);
        setPage(res.pageNum * 1);
        setTotal(res.total * 1);
        // setTableData([]);
      }
    });
  }

  // 重置
  const reset = () => {
    const form = btnRef.current.getForm();
    form.resetFields();
    console.log('清空了表单开始处理逻辑');
    setPage(1);
    setPageSize(10);
    getTableData(params);
  };

  // 查询
  const query = (value: any) => {
    // console.log(value, '表单数据');
    setPage(1);
    const param = {
      ...params,
      ...value,
    };
    getTableData(param);
  };

  // 导出
  const handleExport = () => {
    planExport(params).then(res => {
      console.log(res, '导出结果')
    })
  }

  // 添加计划
  const addPlan = () => {
    console.log(history);
    console.log(history.location.pathname);
    console.log(history.length);
    history.push({
      pathname: '/promotion/promotion_plan/detail',
      query: {
        type: '1'
      }
    })
  };

  // 编辑计划
  const updateClick = (row: any) => {
    history.push({
      pathname: '/promotion/promotion_plan/detail',
      query: {
        type: '2',
        id: row.planId
      }
    })
  }

  // 表格多选
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: PlanColumn[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    }
  };

  // 表格Switch按钮
  const onChange = (checked: boolean, record: any) => {
    console.log(`switch to ${checked}`);
    console.log(record)
    if (checked) {
      // 停用
      const param = {
        planIds: [record.planId * 1],
        status: 2
      };
      changeStatus(param).then(res => {
        console.log(res, '改变状态结果');
        message.success('操作成功！');
        getTableData(params);
      })
    } else {
      // 启用
      const param = {
        planIds: [record.planId * 1],
        status: 1
      };
      changeStatus(param).then(res => {
        console.log(res, '改变状态结果');
        message.success('操作成功！');
        getTableData(params);
      })
    }
  }

  // 页码跳转
  const onPageChange = (page: number, pageSize?: number) => {
    console.log(page, pageSize, '页码跳转');
    setPage(page);
    if (pageSize) {
      setPageSize(pageSize);
    } else {
      setPageSize(10);
    }
    const param = {
      ...params,
      page: page,
      rows: pageSize
    };
    getTableData(param);
  };
  const onShowSizeChange = (page: number, pageSize: number) => {
    console.log(page, pageSize, 'pagesize');
    setPage(page);
    setPageSize(pageSize);
    const param = {
      ...params,
      page: page,
      rows: pageSize
    };
    getTableData(param);
  };

  // 弹窗点击
  const modalClick = (row: any, typeVal: string) => {
    console.log(row, typeVal);
    setType(typeVal);
    if (typeVal === 'del') {
      setDelTitle('确认删除该计划吗？');
      setDelText('删除后，该计划下的单元、关键词、创意也被删除。');
    }
    setRecord(row);
    setModalFlag(true);
  };

  // 其余弹窗确定
  const handleOk = () => {
    console.log(record, '其余弹窗确定');
    if (type === 'del') {
      const param = [record.planId * 1]
      delPlan(param).then(res => {
        console.log(res, '删除账号结果');
        setType('interfaceEnd');
        setEndText('删除成功！');
        setEndTitle('');
        setModalFlag(true);
      })
    }
  };

  // 弹窗知道了按钮点击
  const sureClick = () => {
    setModalFlag(false);
    getTableData(params);
  };

  useEffect(() => {
    getTableData(params);
    getPlatOptions();
  }, []);
  return (
    <>
      <Query flag queryList={queryList} queryClick={query} resetClick={reset} ref={btnRef} selectProp={selectProp} />
      <Row>
        <Col flex="auto">
          <Table<PlanColumn>
            dataSource={tableData}
            rowSelection={{
              ...rowSelection,
            }}
            columns={columns}
            pagination={false}
            rowKey={(record) => record.id}
            // locale={{ emptyText: "空空如也呀~" }}
            scroll={{ y: 600 }}
            className={styles.table}
          ></Table>
        </Col>
      </Row>
      <Footer
        footer={styles.footer}
        length={total}
        current={page}
        pageSize={pageSize}
        pageSizeOptions={['10', '20', '50']}
        onChange={onPageChange}
        onShowSizeChange={onShowSizeChange}
        buttonGroup={
          <>
            {/* <Button className={styles.paddingBtn}>启用</Button>
            <Button className={styles.paddingBtn}>暂停</Button>
            <Button className={styles.paddingBtn}>删除</Button>
            <Button className={styles.paddingBtn}>数据对比</Button> */}
            <Button className={styles.addBtn} onClick={addPlan}>添加计划</Button>
            <Button onClick={handleExport}>导出数据</Button>
          </>
        }
      />
      <ModalComp
        modalFlag={modalFlag}
        setModalFlag={setModalFlag}
        type={type}
        width={400}
        ref={btnRef}
        delTitle={delTitle}
        delText={delText}
        endTitle={endTitle}
        endText={endText}
        handleOk={handleOk}
        sureClick={sureClick}
      />
    </>
  );
}
